package com.feeyo.groundservice.base_util

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Rect
import android.graphics.pdf.PdfDocument
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.View
import android.view.Window
import androidx.annotation.RequiresApi
import androidx.core.view.drawToBitmap
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.Utils
import java.io.File
import java.io.FileOutputStream

/**
 *作者：70893 on 2025-09-17
 *描述：文件类型
 */


/**
 * 保存文件
 * **/
fun saveToFile(msg: String, fileName: String) {
    val cache = File(Utils.getApp().externalCacheDir, "log")
    if (!cache.exists()) {
        cache.mkdirs()
    }
    val targetFile = File(cache, fileName)
    FyLog.e("缓存的文件地址", targetFile.absolutePath)
    if (FileUtils.createOrExistsFile(targetFile)) {
        FileIOUtils.writeFileFromString(targetFile, msg + "\n", true)

    }
}


/**将view转换成pdf**/
fun View.viewToPdf() {
    val document = PdfDocument()
    val pageInfo = PdfDocument.PageInfo.Builder(width, height, 1).create()
    val page = document.startPage(pageInfo)
    this.draw(page.canvas)
    document.finishPage(page)
    document.writeTo(FileOutputStream(getFileCachePath("${System.currentTimeMillis()}.pdf")))
    document.close()
}

fun getFileCachePath(fileName: String): String? {
    val cache = PathUtils.getInternalAppCachePath()
    val targetFile = File(cache, fileName)
    FileUtils.createOrExistsFile(targetFile)
    return targetFile.absolutePath
}

fun View.viewToBitmap(activity: Activity): Bitmap {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        this.draw2Bitmap(activity.window)
    } else {
        this.drawToBitmap(Bitmap.Config.ARGB_8888)
    }
}

@RequiresApi(Build.VERSION_CODES.O)
private fun View.draw2Bitmap(window: Window): Bitmap {

    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val location = IntArray(2)
    getLocationInWindow(location)
    FyLog.e("bitmap", "${this.width}-----${this.height}")
    PixelCopy.request(
        window,
        Rect(location[0], location[1], location[0] + width, location[1] + height),
        bitmap, {
            if (it == PixelCopy.SUCCESS) {
                FyLog.e("bitmap", "将布局转为图片成功")
            }
        }, Handler(Looper.getMainLooper())
    )
    return bitmap
}
